<template>
  <div v-title="'文章管理 - 世外生活运营平台'" class="MkArticleMgt">
    <mk-breadcrumb  :breadcrumb-data="breadcrumbData"></mk-breadcrumb>
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-fixedHeightSmall)+'px'}]">
    <div class=" PublicListStyle">
      <mk-search-component :formArr="formArr"  inputPlaceholder = "标题" @startSearch="fun_call_search">
        <span slot="slot_1">
           <el-button type="primary" size="" @click="handleAdd" class='floatRight btn-create'>写文章</el-button>
        </span>
        <div  slot="slot_2" class="search-result-amount textAlignRight">
          <el-button type="primary" size="" @click="handleAdd" class='floatRight btn-create'>写文章</el-button>
        </div>
      </mk-search-component>

      <div class='tabContainer allArticleList'  v-loading="loadingTab"
           element-loading-text="拼命加载中">
        <div class="primary_bg trHasCursor">
          <el-table
            :data="dataArr.elements"
            style="width: 100%"
            @row-click='showArticleDetail'>
            <el-table-column
              prop="title"
              label="标题"
              show-overflow-tooltip
              width="200">
            </el-table-column>
            <el-table-column
              prop="siteName"
              label="所属站点"
              show-overflow-tooltip
              width="">
            </el-table-column>
            <el-table-column
              prop="category.name"
              label="分类"
              width=""
            >
            </el-table-column>
            <el-table-column
              prop="positions"
              label="展示位置"
              width=""
              show-overflow-tooltip
            >
              <template slot-scope='scope'>
                {{scope.row.positions | positions}}
                </template>
            </el-table-column>
            <el-table-column
              prop="publishTime"
              label="发布时间"
              width="160"
            >
              <template slot-scope="scope">
                {{scope.row.publishTime | formatDate('yyyy-MM-dd HH:mm')}}
                </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              width=""
            >
              <template slot-scope="scope">
                {{scope.row.status | status }}
                </template>
            </el-table-column>
            <el-table-column
              prop=""
              label=""
              width='260'>
              <template slot-scope='scope'>
                <template v-if="scope.row.dataSource == 'OPERATION'">
                  <template v-if="scope.row.status == 'Published'">
                    <el-button type="text" v-if="scope.row.top" @click.stop="handleUnTop(scope.row.id,scope.row.siteId)">取消置顶</el-button>
                    <el-button type="text" v-else @click.stop="handleTop(scope.row.id,scope.row.siteId)">置顶</el-button>
                    <el-button type="text" @click.stop="handleDisable(scope.row.id,scope.row.siteId)">下架</el-button>
                    <el-button type="text" @click.stop="revokeArticle(scope.row.id,scope.row.siteId)">撤回</el-button>
                  </template>
                  <el-button type="text" @click.stop="handlePub(scope.row.id,scope.row.siteId)"  v-else-if="scope.row.status == 'Draft' ||scope.row.status == 'Revoked'">发布</el-button>
                  <el-button type="text" @click.stop="handleEnable(scope.row.id,scope.row.siteId)" v-else-if="scope.row.status == 'Disabled'">上架</el-button>
                  <el-button type="text" @click.stop="deleteArticle(scope.row.id)">删除</el-button>
                </template>
                <template v-else>
                  <template v-if="scope.row.status=='Published'">
                    <el-button type="text" v-if="scope.row.top" @click.stop="handleUnTop(scope.row.id,scope.row.siteId)">取消置顶</el-button>
                    <el-button type="text" v-else @click.stop="handleTop(scope.row.id,scope.row.siteId)">置顶</el-button>
                    <el-button type="text" @click.stop="handleDisable(scope.row.id,scope.row.siteId)">下架</el-button>
                  </template>
                  <el-button type="text" v-else-if="scope.row.status == 'Disabled'" @click.stop='handleEnable(scope.row.id,scope.row.siteId)'>上架</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          v-if='dataArr.elements.length>0'
          @current-change="loadData"
          :current-page="dataArr.page"
          :page-size="dataArr.size"
          layout="total, prev, pager, next"
          :total="dataArr.totalAmount">
        </el-pagination>
      </div>
    </div>
    </el-scrollbar>
  </div>

</template>

<script>
  import MkBreadcrumb from '../../../components/MkBreadcrumb.vue'
  import { mapState } from 'vuex'
  import articleService from '../../../services/article'
  export default {
    name: 'MkArticleMgt',
    components: {
      MkBreadcrumb
    },
    filters: {
      positions(value) {
        var objs = value.split(",");
        var result = [];
        for(var i=0; i < objs.length; i++) {
          switch (objs[i]) {
            case 'COMMUNITY_HEADLINES' : result.push('热点资讯'); break;//
            case 'COMMUNITY_ANNOUNCEMENT' : result.push( '社区公告'); break;
//            case 'ARTICLE_FOR_ACTIVE': result+='活动入口';break;
            case 'HEALTH_DIET': result.push('健康食谱');break;
          }
        }
        return result.join(',');
      },
      status(value) {
        switch (value) {
          case 'Published' : return '已发布';
          case 'Draft' : return '草稿';
          case 'Revoked' : return '已撤回';
          case 'WaitPublish': return '待发布';
          case 'Disabled': return '已下架';
          default: return '';
        }
      },
      formatDate (value,type) {
        if(value==='' || value===null || value===0){
          return '';
        }
        let date=new Date(value);
        return date.pattern(type)
      }
    },
    computed:mapState({
      bodyHeight: state => state.global.bodyHeight,
      fixedHeightSmall: state => state.global.fixedHeightSmall
    }),
    mounted: function() {
      this.$set(this.formArr,0,{
        formLabel:'展示位置',
        searchName:'position',
        dataType:'string',
        componentType:'Select',
        optionsArr: [
          {name:'热点资讯',value:'COMMUNITY_HEADLINES'},
          {name:'社区公告',value:'COMMUNITY_ANNOUNCEMENT'},
          {name:'健康食谱',value:'HEALTH_DIET'}
        ]
      });
      this.$set(this.formArr,2,{
        formLabel:'状态',
        searchName:'status',
        dataType:'string',
        componentType:'Select',
        optionsArr: [
          {name:'已发布',value:'Published'},
          {name:'草稿',value:'Draft'},
          {name:'已撤销',value:'Revoked'},
          {name:'待发布',value:'WaitPublish'},
          {name:'已下架',value:'Disabled'}
        ]
      })
      this.loadSiteTreeData();
      this.$store.dispatch('loadArticleItem');
    },

    activated(){
      this.loadData(1);
    },

    methods : {
      fun_call_search(search,input) {
        this.searchCondition.position = search.position;
        this.searchCondition.siteId = search.siteArr[search.siteArr.length - 1];
        this.searchCondition.status = search.status;

        this.searchCondition.title = input;

        this.loadData(1);
      },
      showArticleDetail(row, event, column) {
        this.$router.push({name: 'MkAddArticle', params: {id: row.id,dataSource:row.dataSource,siteName:row.siteName}});
      },
      handleDisable(value,siteId) {
        this.$confirm('您确定要下架吗?', '下架', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'confirmBox_warning'
        }).then(() => {
          articleService.disableArticle({id:value,siteId:siteId},data=>{
            this.$message.success('下架成功');
            this.loadData();
          })
        }).catch(() => {
        });

      },
      handleEnable(value,siteId) {
        this.$confirm('您确定要上架吗?', '上架', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'confirmBox_warning'
        }).then(() => {
          articleService.enableArticle({id:value,siteId:siteId},data=>{
            this.$message.success('上架成功');
            this.loadData();
          })
        }).catch(() => {
        });

      },
      handleAdd () {
        this.$router.push({name: 'MkAddArticle'});
      },
      handlePub (value,siteId) {
        this.$confirm('发布后该内容将会对外显示，确定要发布吗？', '发布', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'confirmBox_warning'
        }).then(() => {
          articleService.publishArticleServer({id:value,siteId:siteId}, (data) => {
            this.$message.success('发布成功');
            this.loadData();
          });
        }).catch(() => {
        });
      },
      handleTop(value,siteId) {
        articleService.topOrUnTopServer({id:value, needTop:true,siteId:siteId}, (data) =>{
          this.$message.success( '置顶成功');
          this.loadData();
        });
      },
      handleUnTop(value,siteId) {
        articleService.topOrUnTopServer({id:value, needTop:false,siteId:siteId}, (data) => {
          this.$message.success('取消置顶成功');
          this.loadData();
        });
      },
      revokeArticle(value,siteId) {
        this.$confirm('撤回后该内容将不会对外显示，确定要撤回吗？', '撤回', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'confirmBox_warning'
        }).then(() => {
          articleService.revokeArticle({id:value,siteId:siteId}, (data) => {
            this.$message.success( '撤回成功');
            this.loadData();
          });
        }).catch(() => {
        });
      },
      deleteArticle(value) {
        this.$confirm('删除该内容后将不能恢复，确定要删除吗?', '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'confirmBox_warning'
        }).then(() => {
          articleService.deleteArticleServer({id : value}, (data) => {
            this.$message.success('删除成功');
            if (this.dataArr.page != 1 && (this.dataArr.totalAmount == (this.dataArr.page - 1) * (this.dataArr.size) + 1)) {
              this.searchCondition['page.pn'] = this.searchCondition['page.pn'] - 1;
            }
            this.loadData();
          });
        }).catch(() => {
        });
      },
      loadData(page) {
        if(page) {
            this.searchCondition['page.pn'] = page;
        }
        this.loadingTab = true;
        articleService.loadArticleListServer(this.searchCondition,data => {
            this.dataArr = data.data;
            this.loadingTab = false;
        })
      },
      loadSiteTreeData() {
        this.$store.dispatch('loadSiteTree',{fields:'id,name'}).then(data =>{
          let arr = [{id:'',name:'全部'}];
          if(data.data.children){
            for(var i=0;i<data.data.children.length;i++) {
              let item = data.data.children[i];
              if(item.children && item.children.length>0) {
                arr.push(item);
              }
            }
          }
          this.$set(this.formArr,1,{
            formLabel:'站点',
            searchName:'siteArr',
            dataType:'array',
            componentType:'Cascader',
            changeOnSelect:false,
            optionsArr:arr ,
            defaultProps:{
              label:'name',
              value: 'id',
              children: 'children'
            }
          })
        });
      },
    },
    data() {
      return {
        formArr: [],
        loadingTab: false,
        searchCondition: {
          'page.pn': 1,
          'page.size': 10,
          title: '',
          position: '',
          siteId: '',
          status: '',
        },
        breadcrumbData: {
          list: [
             {
              name: '运营',
              path: null,
               clickAble: false
            }, {
              name: '文章管理',
              path: null,
              clickAble: false
            }
         ],
          returnData: {
            isReturn: false, path: null
          },
          iconName: 'operation-icon',
        },
        dataArr: {
          page: '',
          size: '',
          totalAmount: '',
          totalPages: '',
          elements: []
        }
      }
    }
  }
</script>

<style lang="less">
  .MkArticleMgt{
    .allArticleList{
      .el-button{
        padding: 0;
        padding-right: 5px;
      }
    }
  }
</style>
